package com.example.service.impl;

import com.example.service.RefreshScopeService;
import com.example.service.SysCuratorService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RefreshScopeServiceImpl implements RefreshScopeService, InitializingBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysCuratorService sysCuratorService;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initConfigPath();
        this.loadProperties();
        this.initListener();
    }

    @Override
    public void initConfigPath() {
        if (!this.sysCuratorService.isExistNode(CONFIG)) {
            this.sysCuratorService.createNode(CreateMode.PERSISTENT, CONFIG);
        }
    }

    @Override
    public void initListener() {
        this.sysCuratorService.watchNode(CONFIG, new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED || event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    String path = event.getData().getPath().replace(CONFIGS, "");
                    byte[] data = event.getData().getData();
                    System.setProperty(path, new String(data));
                    logger.warn("监听配置的变化, key: {} , value: {}", path, new String(data));
                }
            }
        });
    }

    @Override
    public void loadProperties() {
        List<String> nodes = this.sysCuratorService.getNodeChild(CONFIG);
        for (String path : nodes) {
            String data = this.sysCuratorService.getNodeData(CONFIGS + path);
            System.setProperty(path, data);
        }
    }
}
